package com.javaclimb.drug.common;

import com.javaclimb.drug.entity.UploadInfo;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *
 * </P>
 *
 * @Author 樊森草
 * @Date 2022-4-2 11:10
 * @fileName
 * @Version 1.0.0.0
 */
public class UploadUtils {
    //定义一个上传文件的路径
    private static final String BASE_PATH = "E:\\Tomcat\\apache-tomcat-8.0.53\\webapps\\upload";
    //定义文件服务器的访问地址
    private static  final String SERVER_PATH="http://localhost:8080/upload/";
    public static UploadInfo upload(MultipartFile file){
        UploadInfo uploadInfo = new UploadInfo();
        //获取图片名称
        String fileName = file.getOriginalFilename();
        uploadInfo.setFileName(fileName);
        //获取最后一个.的位置
        int lastIndexOf = fileName.lastIndexOf(".");
        //获取文件的后缀名
        String suffix = fileName.substring(lastIndexOf);
        uploadInfo.setSuffix(suffix);
        System.out.println("suffix = " + suffix);
        //生产一个随机id
        String uuid= UUID.randomUUID().toString().replace("-","");
        //新的文件名称
        String newFileName = uuid +"-"+ fileName;
        //创建一个文件实例对象
        File img = new File(BASE_PATH,newFileName);
        //上传该文件
        try {
            file.transferTo(img);
        } catch (IOException e) {
            return null;
        }
        System.out.println("返回的数据："+SERVER_PATH+newFileName);
        uploadInfo.setFilePath(BASE_PATH);
        uploadInfo.setFileServerPath(SERVER_PATH+newFileName);
        return uploadInfo;
    }
}
